package org.bmi.gwt.examples.serverevent.client;

import org.bmi.gwt.examples.serverevent.shared.MyTestProxy;
import org.bmi.gwt.mi.client.channel.Connection;
import org.bmi.gwt.mi.client.events.ConnectionHandler;
import org.bmi.gwt.mi.shared.BroadChannel;
import org.bmi.gwt.mi.shared.Channel;
import org.bmi.gwt.mi.shared.callbacks.BindCallback;
import org.bmi.gwt.mi.shared.exceptions.InvalidArgumentException;
import org.bmi.gwt.mi.shared.exceptions.MiException;
import org.bmi.gwt.mi.shared.exceptions.NameParseException;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;

public class MiEventTest implements EntryPoint
{
	/*
	 * This example attempts to explain how a method invocation event handler
	 * (MiEventhandler) works providing a very simple example.
	 */

	@Override
	public void onModuleLoad()
	{
		Connection.createConnection(new ConnectionHandler()
		{
			@Override
			public void onConnectionBegin(final Connection connection)
			{
				try
				{
					Channel qListen = connection.getChannel("org.bmi.gwt.mi.test.event");

					qListen.bind(new BindCallback()
					{
						@Override
						public void onError(MiException error)
						{
							GWT.log("An error occurred: " + error);
						}

						@Override
						public void onBound(Channel channel)
						{
							try
							{
								final BroadChannel qSend = connection.getChannel("org.bmi.gwt.mi.test.event");
								final MyTestProxy proxy = qSend.proxyToNewObject(MyTestProxy.class,
										"a string sent to constructor...");

								final TextBox echoBox = new TextBox();

								Button sendButton = new Button("Send", new ClickHandler()
								{
									public void onClick(ClickEvent event)
									{
										proxy.process(echoBox.getValue());
									}
								});

								RootPanel.get().add(echoBox);
								RootPanel.get().add(sendButton);
							}
							catch (InvalidArgumentException e)
							{
								GWT.log("", e);
							}
							catch (NameParseException e)
							{
								GWT.log("", e);
							}
						}
					});
				}
				catch (NameParseException e)
				{
					GWT.log("", e);
				}
			}

			@Override
			public void onException(Exception e)
			{
				GWT.log("an error occurred: ", e);
			}
		});
	}
}
